﻿using AutoMapper;
using IoTAdapter.BaseCore.Enums;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Xml.Linq;
using Warehouse.Entites;
using Warehouse.Services.Repository;
using WCS.Entities.Api;
using WCS.ViewModels;

namespace JuionWareHouse.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WareHouseController : ControllerBase
    {
        private readonly ILogger<WareHouseController> _logger;
        private readonly Repository<WareHouse> HouseRepository;

        public WareHouseController(ILogger<WareHouseController> logger, Repository<WareHouse> houseRepository)
        {
            _logger = logger;
            HouseRepository = houseRepository;
        }

        #region 添加
        /// <summary>
        /// 创建库位
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Create([FromBody] WareHouseDTO model)
        {
            try
            {
                var warehouse = new WareHouse
                {
                    WHName = model.WHName,
                    WHNumber = model.WHNumber,
                    PalletNumber = model.PalletNumber,
                    Capacity = model.Capacity,
                    CurrentQuantity = model.CurrentQuantity,
                    CrownPrincce = model.CrownPrincce,
                    WHStare = model.WHStare,
                    Area = model.Area,
                    Enable = model.Enable,
                    TargetPlatoon = model.TargetPlatoon,
                    TargetColumn = model.TargetColumn,
                    TargetLayer = model.TargetLayer,
                };
                var isOk = await HouseRepository.AddAsync(warehouse);
                if (!isOk)
                {
                    return ApiResultHelp.Error("添加失败");
                }

                return ApiResultHelp.Success(warehouse);
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"添加出错!服务器发生错误:{ex.Message}");
            }
        }
        #endregion

        #region 查询
        /// <summary>
        /// 查询所有库位
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetAllStorage()
        {
            try
            {
                var storages = await HouseRepository.QueryAsync();
                return ApiResultHelp.Success(storages);
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"获取所有出错:{ex.Message}");
            }
        }
        /// <summary>
        /// 分页查找
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页大小</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetParksByPage(int page, int limit, [FromQuery] string? query)
        {
            RefAsync<int> total = 0;
            try
            {
                if (query != null)
                {
                    JObject jobject = JObject.Parse(query);
                    var models = new List<IConditionalModel>();
                    foreach (var key in jobject.Properties())
                    {
                        if (string.IsNullOrEmpty(key.Value.ToString()))
                            continue;
                        if (key.Value.ToString() == "true" || key.Value.ToString() == "false")
                            key.Value = key.Value.ToString() == "true" ? "1" : "0";
                        else
                            models.Add(new ConditionalModel()
                            { FieldName = key.Name, FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.Like });
                    }
                    var parks = await HouseRepository.QueryAsync(models, page, limit, total);
                    return ApiResultHelp.Success(new { list = parks, total = total.Value });
                }
                else
                {
                    var parks = await HouseRepository.QueryAsync(page, limit, total);
                    return ApiResultHelp.Success(new { list = parks, total = total.Value });
                }
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"查询出错:{ex.Message}");
            }
        }
		/// <summary>
		/// 获取所有空库位数据
		/// </summary>
		/// <returns></returns>
		[HttpGet]
        public async Task<ApiResult> GetAllNullStorage()
        {
            try
            {
                var nullStorageCount = 0;
                var storages = await HouseRepository.QueryAsync();
                foreach (var storage in storages)
                {
                    if (storage.CurrentQuantity != storage.Capacity)
                    {
                        nullStorageCount += storage.Capacity - storage.CurrentQuantity;
                    }
                }
                return ApiResultHelp.Success(nullStorageCount);
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"获取所有空库位出错:{ex.Message}");
            }
        }

        /// <summary>
        /// 检测是否存在
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet()]
        public async Task<ActionResult<ApiResult>> Check([FromQuery] string query)
        {
            JObject jobject = JObject.Parse(query);
            try
            {
                List<IConditionalModel> models = new List<IConditionalModel>();

                foreach (var key in jobject.Properties())
                {
                    if (key.Name.ToString().ToLower() == "id" && jobject.Count > 1)
                    {
                        continue;
                    }
                    models.Add(new ConditionalModel()
                    {
                        FieldName = key.Name,
                        FieldValue = key.Value.ToString(),
                        ConditionalType = ConditionalType.Equal
                    });
                }
                var parks = await HouseRepository.Context.Queryable<WareHouse>().Where(models).ToListAsync();
                if (jobject.ContainsKey("id") && jobject.Count > 1)
                {
                    var count = parks.Count(x => x.Id != Convert.ToInt32(jobject["id"]?.ToString()));
                    return ApiResultHelp.Success(count);
                }
                return ApiResultHelp.Success(parks.Count);

            }
            catch (Exception e)
            {
                return ApiResultHelp.Error("查找设备出错" + e.Message);
            }

        }
        #endregion

        #region 更新
        /// <summary>
        /// 更新库位点信息
        /// </summary>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ApiResult> Update(string id, WareHouseDTO model)
        {
            var newPark = await HouseRepository.FindAsync(id);
            if (newPark == null)
            {
                return ApiResultHelp.Error("没有找到该库位信息");
            }
            newPark.WHName = model.WHName;
            newPark.WHNumber = model.WHNumber;
            newPark.PalletNumber = model.PalletNumber;
            newPark.Capacity = model.Capacity;
            newPark.CurrentQuantity = model.CurrentQuantity;
            newPark.CrownPrincce = model.CrownPrincce;
            newPark.WHStare = model.WHStare;
            newPark.Area = model.Area;
            newPark.Enable = model.Enable;
            newPark.TargetPlatoon = model.TargetPlatoon;
            newPark.TargetColumn = model.TargetColumn;
            newPark.TargetLayer = model.TargetLayer;
            newPark.Update_time = DateTime.Now;
            
            var isOk = await HouseRepository.UpdateAsync(newPark);
            if (!isOk)
            {
                return ApiResultHelp.Error("修改失败");
            }
            return ApiResultHelp.Success(newPark);
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除库位点通过Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ApiResult> Delete(string id)
        {
            bool b = await HouseRepository.DeleteByIdAsync(id);
            if (!b)
            {
                return ApiResultHelp.Error("删除失败");
            }
            return ApiResultHelp.Success(b);
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的Ids</param>
        /// <returns></returns>
        [HttpDelete()]
        public async Task<ApiResult> DeleteByIds(string[] ids)
        {
            bool b = await HouseRepository.DeleteByIdsAsync(ids);
            if (!b)
            {
                return ApiResultHelp.Error("删除失败");
            }
            return ApiResultHelp.Success(b);
        }
        #endregion
    }
}
